'''
Created on 24 apr 2016

@author: Daniel
'''
from UI.UI_new_startup  import Ui_Dialog_new_startup
from PyQt4                      import QtGui
from utils.utils                import launchMessage
from new_config_dial            import NewConfigDial
import os

class NewStartup(QtGui.QDialog, Ui_Dialog_new_startup):
    def __init__(self, values={}):
        super(NewStartup,self).__init__()
        self.setupUi(self)
        self.initValues = values
        self.setEvents()
        self.initFields()
        
    def initFields(self):
        name = self.initValues.get('name', '')
        path = self.initValues.get('path', '')
        self.lineEdit_exe_path.setText(path)
        self.lineEdit_menu_name.setText(name)
        
    def setEvents(self):
        self.pushButton_exe_path.clicked.connect(self.getFileFromSystem)
        self.buttonBox.accepted.connect(self.acceptConfig)
        self.buttonBox.rejected.connect(self.rejectConfig)
    
    def getFileFromSystem(self):
        dial = NewConfigDial(parent=self)
        pathToAdd = ''
        if dial.exec_() == QtGui.QDialog.Accepted:
            customFlag = dial.radioButton_custom.isChecked()
            pathsToAdd = []
            if customFlag:
                pathsToAdd.append(dial.lineEdit_out_path.text())
            else:
                indexes = dial.listWidget.selectedIndexes()
                for index in indexes:
                    pathsToAdd.append(index.data().toString())
            if len(pathsToAdd) > 1:
                launchMessage('Select only one executable please.')
                return
            else:
                pathToAdd = pathsToAdd[0]
        self.lineEdit_exe_path.setText(pathToAdd)
        baseName = os.path.basename(unicode(pathToAdd))
        name = baseName.split('.')[0]
        written = self.lineEdit_menu_name.text()
        if not written:
            self.lineEdit_menu_name.setText(name)
        
    def acceptConfig(self):
        exePath = self.lineEdit_exe_path.text()
        menuName = self.lineEdit_menu_name.text()
        if not exePath or not menuName:
            launchMessage('Cannot leave empty values!')
        self.accept()
    
    def rejectConfig(self):
        self.reject()
